<template>
  <div class="orgbox">
    <h2 class="header_title">组织创建/编辑 <span @click="dialogVisible = true" v-if="isEdit">批量创建 ></span></h2>
    <div class="_main" v-if="!isEdit"><no-right/></div>
    <div class="cabin" v-if="isEdit">
      <span class="confirmbtn" @click="confirm">确认</span>
      <ul>
        <li>上级组织：{{ defaultDate.superiororganization }}</li>
        <li>组织ID：{{ defaultDate.formid }}</li>
        <li>
          <span>创建级别:</span>
          <div class="_el-ipt" :class="{ 'error': rules.levelTypeError }">
            <el-radio v-model="form.levelType" :disabled="store.state.roleid == 1006"  label="2">编辑下一级</el-radio>
            <el-radio v-model="form.levelType" label="1">编辑本级用户信息</el-radio>
          </div>
        </li>
        <li>
          <span>省份：</span>
          <VDistpicker  
                      ref="VDistpicker"
                      v-if="form.levelType == 2"
                      :province-disabled="store.state.roleid == 1002 || store.state.roleid == 1003 || store.state.roleid == 1004 || store.state.roleid == 1005 || store.state.roleid == 1006"
                      :city-disabled="store.state.roleid == 1003 || store.state.roleid == 1004 || store.state.roleid == 1005 || store.state.roleid == 1006"
                      :area-disabled="store.state.roleid == 1004 || store.state.roleid == 1005 || store.state.roleid == 1006"
                      :province="vt.province"
                      :city="vt.city"
                      :area="vt.area"
                      :placeholders="placeholders"
                      @province="province"
                      @city="city"
                      @area="area"
                      ></VDistpicker>
          <span style="display: inline-block; width: 100%;" v-else>{{ vt.province + '-' + vt.city + '-' + vt.area }}</span>
        </li>
        <li>
          <span>单位电话：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.workTelephoneError }">
            <el-input class="inp" v-number-input v-model="form.workTelephone" placeholder="请输入内容" clearable @blur="setError('rules', 'workTelephone', form)"></el-input>
            <span class="_span" v-if="rules.workTelephoneError">{{ rules.workTelephoneMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.workTelephone }}</span>
        </li>
        <li v-if="store.state.roleid == 1005 && form.levelType == 2">
          <span>院系：</span>
          <div class="_el-ipt"  v-if="form.levelType == 2" :class="{ 'error': rules.collegenameError }">
            <el-input class="inp" v-model="form.collegename" placeholder="请输入内容" clearable @blur="setError('rules', 'collegename', form)"></el-input>
            <span class="_span" v-if="rules.collegenameError">{{ rules.collegenameMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.collegename }}</span>
        </li>
        <li v-if="store.state.roleid == 1005 && form.levelType == 2">
          <span>班级：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.classnameError }">
            <el-input class="inp" v-model="form.classname" placeholder="请输入内容" clearable @blur="setError('rules', 'classname', form)"></el-input>
            <span class="_span" v-if="rules.classnameError">{{ rules.classnameMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.classname }}</span>
        </li>
        <li v-if="store.state.roleid == 1005 && form.levelType == 2">
          <span>部门名称：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.departmentError }">
            <el-input class="inp" v-model="form.department" placeholder="请输入内容" clearable @blur="setError('rules', 'department', form)"></el-input>
            <span class="_span" v-if="rules.departmentError">{{ rules.departmentMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.department }}</span>
        </li>
        <li v-if="store.state.roleid != 1005 || store.state.roleid == 1005 && form.levelType == 1">
          <span>组织名称：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.organizationnameError }">
            <el-input class="inp" v-model="form.organizationname" placeholder="请输入内容" clearable @blur="setError('rules', 'organizationname', form)"></el-input>
            <span class="_span" v-if="rules.organizationnameError">{{ rules.organizationnameMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.organizationname }}</span>
        </li>
        <li>
          <span>单位负责人：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.headOfUnitError }">
            <el-input class="inp" v-model="form.headOfUnit" placeholder="请输入内容" clearable @blur="setError('rules', 'headOfUnit', form)"></el-input>
            <span class="_span" v-if="rules.headOfUnitError">{{ rules.headOfUnitMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.headOfUnit }}</span>
        </li>
        <li v-if="store.state.roleid == 1003 && form.levelType == 2 || store.state.roleid == 1005 && form.levelType == 1">
          <span>学校等级：</span>
          <div class="_el-ipt" v-if="form.levelType == 2" :class="{ 'error': rules.schoolgradeError }">
            <el-select v-model="form.schoolgrade" placeholder="请选择" clearable @change="setError('rules', 'schoolgrade', form)">
              <el-option v-for="item in schoolgradeList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <span class="_span" v-if="rules.schoolgradeError">{{ rules.schoolgradeMessage }}</span>
          </div>
          <span v-else>{{ defaultDate.levelType }}</span>
        </li>
        <li>
          <span>用户名：</span>
          <div class="_el-ipt" :class="{ 'error': rules.usernameError }">
            <el-input class="inp" v-model="form.username" placeholder="请输入内容" clearable @blur="setError('rules', 'username', form)"></el-input>
            <span class="_span" v-if="rules.usernameError">{{ rules.usernameMessage }}</span>
          </div>
        </li>
        <li>
          <span>职位：</span>
          <div class="_el-ipt" :class="{ 'error': rules.positionError }">
            <el-input class="inp" v-model="form.position" placeholder="请输入内容" clearable @blur="setError('rules', 'position', form)"></el-input>
            <span class="_span" v-if="rules.positionError">{{ rules.positionMessage }}</span>
          </div>
        </li>
        <li>
          <span>联系方式：</span>
          <div class="_el-ipt" :class="{ 'error': rules.phoneError }">
            <el-input class="inp" v-number-input v-model="form.phone" placeholder="请输入内容" clearable @blur="setError('rules', 'phone', form)"></el-input>
            <span class="_span" v-if="rules.phoneError">{{ rules.phoneMessage }}</span>
          </div>
        </li>
        <li>
          <span>管理权限：</span>
          <div class="_el-ipt" :class="{ 'error': rules.personinchargeError }">
            <el-select v-model="form.personincharge" placeholder="请选择" clearable @change="setError('rules', 'personincharge', form)">
                <el-option v-if="store.state.roleid == 1001" label="系统组织负责人" value="1"></el-option>
                <el-option v-if="store.state.roleid != 1001" label="组织负责人" value="1"></el-option>
                <el-option label="普通人员" value="2"></el-option>
            </el-select>
            <span class="_span" v-if="rules.personinchargeError">{{ rules.personinchargeMessage }}</span>
          </div>
        </li>
      </ul>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="400px">
        <el-button type="primary" @click="exports">Excel模板文件</el-button>
        <el-upload
            ref="upload"
            :file-list="fileList"
            :limit="1"
            :action="uploadUrl"
            :data="{ userid: store.state.user.userid }"
            :on-exceed="onExceed"
            :on-change="onChange"
            :on-success="onSuccess"
            :on-error="onError"
            accept=".xlsx,.xls"
            class="upload-demo"
            style="margin-left: 15px">
            <el-button
                slot="trigger"
                size="mini"
                type="primary">选择文件，批量上传</el-button>
        </el-upload>
    </el-dialog>
    <!-- ----- -->
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker'
import store from '@/store'
import verificationArr from './organization.js'

  export default {
    name: 'organization',
    components: { VDistpicker },
    data() {
      return {
        store,
        isEdit: true,
        message: '',
        nation: '国家教育局',
        form: {},
        defaultDate: {},
        params: {},
        vt: {}, // 默认显示省市区
        placeholders: { province: '省', city: '市', area: '区' }, // 新增显示
        schoolgradeList: [
          { id: '1', name: '幼儿园' },
          { id: '2', name: '小学' },
          { id: '3', name: '初中' },
          { id: '4', name: '高中' },
          { id: '5', name: '职高' },
          { id: '6', name: '中专' },
          { id: '7', name: '大学' }
          ],
        managepower: '', // 1是管理员，0是普通人员
        rules: {
            levelType: [
                { required: true, message: '请选择创建级别', trigger: 'blur', type: 1 }
            ],
            collegename: [
              { required: true, message: '请输入院系', trigger: 'blur', type: 1 }
            ],
            classname: [
              { required: true, message: '请输入班级', trigger: 'blur', type: 1 }
            ],
            department: [
              { required: true, message: '请输入部门名称', trigger: 'blur', type: 1 }
            ],
            organizationname: [
              { required: true, message: '请输入组织名称', trigger: 'blur', type: 1 }
            ],
            username: [
              { required: true, message: '请输入负责人', trigger: 'blur', type: 1 }
            ],
            schoolgrade: [
                { required: true, message: '请选择学校等级', trigger: 'blur', type: 1 }
            ],
            position: [
              { required: true, message: '请输入职位', trigger: 'blur', type: 1 }
            ],
            phone: [
              { required: true, message: '请输入联系方式', trigger: 'blur', type: 1 },
              { required: true, message: '请输入合法的手机号码', trigger: 'blur', type: 2 }
            ],
            personincharge: [
                { required: true, message: '请选择管理权限', trigger: 'blur', type: 1 }
            ],
            headOfUnit: [
                { required: true, message: '请输入单位负责人', trigger: 'blur', type: 1 }
            ],
            workTelephone: [
                { required: true, message: '请输入单位电话', trigger: 'blur', type: 4 }
            ]
        },
        dialogVisible: false,
        fileList: [],
        uploadUrl: 'http://wcxt.bjyulinkeji.com/user/batchimport'
      }
    },
    mounted() {
      this.getInfo()
    },
    methods: {
      createmul(){
        alert(1)
      },
      confirm(){
        var type = this.form.levelType
        var res = {}
        if (this.params.rtype == 1) {
          for(let item in this.form) {
            this.defaultDate[item] = this.form[item]
          }
          res = this.defaultDate
        } else {
          res = this.form
        }
        if (type == 2 && !res.provinceid) {
          this.$notify.warning('请选择省')
          return
        }
        if (type == 2 && !res.cityid) {
          this.$notify.warning('请选择市')
          return
        }
        if (type == 2 && !res.countyid) {
          this.$notify.warning('请选择区县')
          return
        }
        var valid = true
        var result = []
        var id = store.state.roleid
        if (type == 1) {
          result = id == 1001 ? verificationArr[0] : verificationArr[1]
        } else {
          if (id == 1001) result = verificationArr[2]
          if (id == 1002) result = verificationArr[3]
          if (id == 1003) result = verificationArr[4]
          if (id == 1005) result = verificationArr[5]
        }
        result.map(name => {
            const rs = this.setError('rules', name, this.form)
            if (!rs) valid = rs
        })
        if (!valid) return
        res.cityid = res.cityid * 1
        res.provinceid = res.provinceid * 1
        res.countyid = res.countyid * 1
        res.managepower = res.personincharge
        this.$http('user/saveOrUpdate', res).then(({ code, message }) => {
          if (code == 200) {
            this.$notify.success(this.params.rtype == 0 ? '修改成功' : '创建成功')
            this.$router.push('/organizationAdministration')
          } else {
            this.$notify.success(message)
          }
        })
      },
      getInfo() {
        this.params = Object.keys(this.$route.params).length > 0 ? this.$route.params : { rtype: 1, userid: store.state.user.userid }
        this.$http('user/form', this.params).then(({ data, code, message }) => {
          if (code == 200) {
            this.isEdit = true
            this.vt = { province: data.province, city: data.cityname, area: data.county }
            this.defaultDate = data
            if (this.params.rtype == 0) { // 修改
              this.form = data
            } else {
              this.form = { levelType: '2' }
              if (store.state.roleid == 1006) this.form.levelType = '1'
            }
          } else {
            this.isEdit = false
            this.message = message
          }
        })
      },
      province(code) {
        this.form.province = code.value
        this.form.provinceid = code.code
      },
      city(code) {
        this.form.cityname = code.value
        this.form.cityid = code.code
      },
      area(code) {
        this.form.county = code.value
        this.form.countyid = code.code
      },
      // 错误验证
      setError(rulesName, name, ruleForm, name2) {
          var res = true
          const arr = this[rulesName][name]
          for(var i = 0 ; i < arr.length ; i++) {
              if (arr[i].type == 1) {
                  if (!ruleForm[name]) {
                      res = false
                      this.$set(this[rulesName], name + 'Error', true)
                      this.$set(this[rulesName], name + 'Message', arr[i].message)
                      break;
                  } else {
                      this.$set(this[rulesName], name + 'Error', false)
                  }
              } else if (arr[i].type == 2) {
                  if (!/^1[3456789]\d{9}$/.test(ruleForm[name])) {
                      res = false
                      this.$set(this[rulesName], name + 'Error', true)
                      this.$set(this[rulesName], name + 'Message', arr[i].message)
                      break;
                  } else {
                      this.$set(this[rulesName], name + 'Error', false)
                  }
              } else if (arr[i].type == 3) {
                  if (ruleForm[name] != ruleForm[name2]) {
                      res = false
                      this.$set(this[rulesName], name + 'Error', true)
                      this.$set(this[rulesName], name + 'Message', arr[i].message)
                  } else {
                      this.$set(this[rulesName], name + 'Error', false)
                  }
              } else if (arr[i].type == 4) {
                  if (!ruleForm[name]) {
                      res = false
                      this.$set(this[rulesName], name + 'Error', true)
                      this.$set(this[rulesName], name + 'Message', '请输入座机号码')
                  } else if (!/^[\d-]{1,13}$/.test(ruleForm[name])) {
                      res = false
                      this.$set(this[rulesName], name + 'Error', true)
                      this.$set(this[rulesName], name + 'Message', '请输入合法的座机号码，最长13位')
                  } else {
                      this.$set(this[rulesName], name + 'Error', false)
                  }
              }
          }
          return res
      },
      exports() {
          location.href = 'http://wcxt.bjyulinkeji.com/user/template/export?userid=' + store.state.user.userid
      },
      onExceed() {
          this.$notify.warning('只能选择一个文件上传，若要更换文件，请先移除之前的文件')
      },
      // 文件变更
      onChange(file) {
          this.fileList = [].concat(file)
      },
      // 上传成功
      onSuccess({ code, message }) {
          if (code != 200) {
              this.$notify.error(message)
              return
          }
          this.$notify.success('导入文件成功')
          this.dialogVisible = false
          this.$router.push('/organizationAdministration')
      },
      // 上传失败
      onError({ code, message }) {
          this.$notify.error(message)
      }
    }
  }
</script>

<style lang="less" scoped>
  .orgbox{
    .title{
      font-size: 16px;
      color: #fff;
      line-height: 44px;
      span{
        float: right;
        font-size: 13px;
        color: #4353da;
        cursor: pointer;
        &:hover{
          color: #fff;
        }
      }
    }
    .cabin{
      position: relative;
      background-color: #000418;
      padding: 20px;
      margin-top: 20px;
      .confirmbtn{
        position: absolute;
        right: 50px;
        bottom: 40px;
        font-size: 13px;
        color: #fff;
        background-color: #1e29ac;
        padding: 0 20px;
        cursor: pointer;
        line-height: 34px;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;
        &:hover{
          background-color: #4d57d2;
        }
      }
      ul{
        width: 100%;
        overflow: hidden;
        li{
          display: block;
          // overflow: hidden;
          display: flex;
          flex-direction: initial;
          width: 100%;
          font-size: 14px;
          color: #fff;
          line-height: 34px;
          margin-bottom: 34px;
          span{
            float: left;
            display: inline-block;
            width: 100px;
            font-size: 14px;
            color: #fff;
            line-height: 40px;
          }
          .el-select{
            float: left;
            margin-right: 20px;
          }
          /deep/ .el-input__inner{
            background-color: transparent;
            font-size: 13px;
            color: #fff;
          }
          .inp{
            float: left;
            display: inline-block;
            width: 200px;
          }
        }
      }
    }
  }
  .distpicker-address-wrapper /deep/ select {
    background-color: transparent;
    border: 1px solid #dddfe7;
    color: #fff;
  }
  .distpicker-address-wrapper /deep/ select:focus {
    border: 1px solid #4061ce;
  }

  ._el-ipt {
      position: relative;
      float: left;
      ._span {
          position: absolute;
          left: 0;
          font-size: 12px;
          bottom: -32px;
          width: 300px !important;
      }
  }

  ._el-ipt.error {
      ._span {
          color: #F56C6C;
      }
      /deep/ .el-input__inner {
          border-color: #F56C6C;
      }
  }

  // 省市区三级联动
  /deep/ .distpicker-address-wrapper option {
    color: #000 !important;
  }

  /deep/ .distpicker-address-wrapper select {
    min-width: 170px;
  }

  /deep/ .upload-demo,
  /deep/ .el-dialog__body {
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  /deep/ .upload-demo {
    .el-button {
      height: 40px;
    }
    .el-upload-list__item-name,
    .el-upload-list__item-name .el-icon-document {
        color: #fff !important;
    }
  }

  /deep/ .el-dialog, 
  /deep/ .el-pager li {
    background-color: transparent;
  }

  /deep/ .el-dialog__header,
  /deep/ .el-dialog__body {
    border: 1px solid #0070ff;
    background-color: rgba(0, 112, 255, 0.2);
  }

  /deep/ .el-dialog__header {
    border-bottom: none;
    .el-dialog__title {
        display: inline-block;
        width: 100%;
        text-align: center;
        color: #fff;
    }
  }

  /deep/ .el-dialog__body {
    border-top: none;
  }

</style>
